using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Write.Controllers
{
    /// <summary>
    /// 文件上传控制器
    /// 提供图片等文件上传功能
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class FileUploadController : ControllerBase
    {
        private readonly ILogger<FileUploadController> _logger;
        private readonly IWebHostEnvironment _environment;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="environment">环境信息</param>
        public FileUploadController(ILogger<FileUploadController> logger, IWebHostEnvironment environment)
        {
            _logger = logger;
            _environment = environment;
        }

        /// <summary>
        /// 上传轮播图图片
        /// </summary>
        /// <param name="file">上传的图片文件</param>
        /// <returns>上传结果，包含图片URL</returns>
        [HttpPost("carousel/upload")]
        public async Task<APIResult<object>> UploadCarouselImage(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return new APIResult<object>
                    {
                        Code = APIEnum.Fail,
                        Message = "请选择要上传的图片",
                        Data = null!
                    };
                }

                // 验证文件类型
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (!allowedExtensions.Contains(extension))
                {
                    return new APIResult<object>
                    {
                        Code = APIEnum.Fail,
                        Message = "只允许上传图片文件（jpg, jpeg, png, gif, bmp, webp）",
                        Data = null!
                    };
                }

                // 验证文件大小 (最大2MB)
                if (file.Length > 2 * 1024 * 1024)
                {
                    return new APIResult<object>
                    {
                        Code = APIEnum.Fail,
                        Message = "图片大小不能超过2MB",
                        Data = null!
                    };
                }

                // 创建上传目录
                var uploadPath = Path.Combine(_environment.WebRootPath, "uploads", "carousel");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid():N}{extension}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回完整URL，确保前端能正确显示
                var imageUrl = $"http://localhost:5049/uploads/carousel/{fileName}";

                _logger.LogInformation("轮播图图片上传成功：{FileName}", fileName);

                return new APIResult<object>
                {
                    Code = APIEnum.OK,
                    Message = "图片上传成功",
                    Data = new { url = imageUrl }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "轮播图图片上传失败");
                return new APIResult<object>
                {
                    Code = APIEnum.Fail,
                    Message = "图片上传失败，请稍后重试",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 上传医院图片
        /// </summary>
        /// <param name="file">上传的图片文件</param>
        /// <returns>上传结果，包含图片URL</returns>
        [HttpPost("hospital/upload")]
        public async Task<APIResult<object>> UploadHospitalImage(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return new APIResult<object>
                    {
                        Code = APIEnum.Fail,
                        Message = "请选择要上传的图片",
                        Data = null!
                    };
                }

                // 验证文件类型
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (!allowedExtensions.Contains(extension))
                {
                    return new APIResult<object>
                    {
                        Code = APIEnum.Fail,
                        Message = "只允许上传图片文件（jpg, jpeg, png, gif, bmp, webp）",
                        Data = null!
                    };
                }

                // 验证文件大小 (最大2MB)
                if (file.Length > 2 * 1024 * 1024)
                {
                    return new APIResult<object>
                    {
                        Code = APIEnum.Fail,
                        Message = "图片大小不能超过2MB",
                        Data = null!
                    };
                }

                // 创建上传目录
                var uploadPath = Path.Combine(_environment.WebRootPath, "uploads", "hospital");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid():N}{extension}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回完整URL，确保前端能正确显示
                var imageUrl = $"http://localhost:5049/uploads/hospital/{fileName}";

                _logger.LogInformation("医院图片上传成功：{FileName}", fileName);

                return new APIResult<object>
                {
                    Code = APIEnum.OK,
                    Message = "图片上传成功",
                    Data = new { url = imageUrl }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "医院图片上传失败");
                return new APIResult<object>
                {
                    Code = APIEnum.Fail,
                    Message = "图片上传失败，请稍后重试",
                    Data = null!
                };
            }
        }
    }
}